import { View, Button } from '@tarojs/components';
import './index.scss';
import IconFont from '../../iconfont/index.weapp';
import Taro from '@tarojs/taro';
import { useEffect, useState } from 'react';
import { STATUS, STATUS_NAME_EN, courseInfo } from '../../../configProvider';
import Portrait from '../../../components/Portrait';
import CourseCard from '../../../components/Card/CourseCard';

const Home: React.FC = () => {
  const [name, setName] = useState('');
  const [code, setCode] = useState('');
  const [status, setStatus] = useState(STATUS.STUDENT);
  const [checkingList, setCheckingList] = useState<courseInfo[]>([]);

  useEffect(() => {
    init();
  }, []);

  const init = async () => {
    const [statusData, codeData, nameData] = await Promise.all([
      Taro.getStorage({ key: 'status' }),
      Taro.getStorage({ key: 'code' }),
      Taro.getStorage({ key: 'name' }),
    ]);

    if (!codeData.data) {
      Taro.navigateTo({
        url: '../selectStatus/index',
      });
      return;
    }

    setStatus(statusData.data);
    setCode(codeData.data);
    setName(nameData?.data || '');

    Taro.cloud
      .callFunction({
        name: 'getCheckingCourse',
        data: {
          code: codeData.data,
          status: STATUS_NAME_EN[statusData.data],
        },
      })
      .then((res: any) => {
        console.log('getCheckingCourse result', res.result);
        setCheckingList(res.result);
      })
      .catch(err => {
        console.log('fail to call getCheckingCourse', err);
      });
  };

  const changeStatus = () => {
    Taro.navigateTo({
      url: '../selectStatus/index',
    });
  };

  const reLoad = () => {
    Taro.reLaunch({
      url: '../index/index',
    });
  };

  const handleClick = (index: number) => {
    if (status === STATUS.STUDENT) {
      handleStudentClick(index);
    } else if (status === STATUS.TEACHER) {
      handleTeacherClick(index);
    }
  };

  const handleStudentClick = (index: number) => {
    const selectedCourse = checkingList[index];
    const courseId = selectedCourse._id;

    Taro.navigateTo({
      url: `../checkStudentView/index?courseId=${courseId}&code=${code}`,
    });
  };

  const handleTeacherClick = (index: number) => {
    const selectedCourse = checkingList[index];
    const courseId = selectedCourse._id;
    Taro.navigateTo({
      url: `../checkTeacherView/index?courseId=${courseId}`,
    });
  };
  const clearStorage = () => {
    Taro.clearStorage();
    Taro.reLaunch({ url: '../index/index' });
  }

  return (
    <View className='home'>
      <View className='user-info'>
        <View className='user-info-left'>
          <View className='profile'>
            <Portrait status={status} size={90} />
          </View>
        </View>
        <View className='user-info-right'>
          <View className='user-status-edit-icon' onClick={changeStatus}>
            切换身份
            <IconFont name='user' size={40} color='#999' />
          </View>
          <View className='user-info-name'>{name ? name : '未知用户名'}</View>
          <View className='user-info-id'>{code ? code : '未知ID'}</View>
        </View>
      </View>

      <Button onClick={reLoad} className='common-button'>
        刷新
      </Button>
      <Button onClick={clearStorage} className='common-button'>
        清空本地缓存
      </Button>

      <View className='consult-list'>
        {checkingList.map((value, index) => (
          <CourseCard key={index} active name={value.courseName}
            startTime={value.startTime} endTime={value.endTime} weekday={value.weekday}
            teacher={value.teacher} startDate={value.startDate} endDate={value.endDate}
            status={status} onClick={() => { handleClick(index); }} />
        ))}
      </View>
    </View>
  );
};

export default Home;
